import React, { useState, useCallback } from "react";
import { NextPage } from "next";
import {
  Modal,
  Badge,
  Divider,
  Select,
  message,
  Input,
  Popconfirm,
  notification,
} from "antd";

import { AdminLayout } from "@/layout";
import dayjs from "dayjs";
import { SPTDataTable } from "@/components/SPTDataTable";
import { CommentApi } from "@/api/comment";
import { useSettings } from "@/hooks/settings";
import { SettingApi } from "@/api/setting";
import Link from "next/link";

const Comment: NextPage = () => {
  const setting = useSettings();
  // 全部评论
  const [comments, setComments] = useState(null);
  const [loading, setLoading] = useState(false);
  // 搜索参数
  const [params, setParams] = useState(null);
  // 当前选择的评论
  const [currentComment, setCurrentComment] = useState(null);
  // 回复的评论内容
  const [replyContent, setreplyContent] = useState(null);

  const columns = [
    {
      title: "称呼",
      key: "name",
      dataIndex: "name",
    },
    {
      title: "联系方式",
      key: "email",
      dataIndex: "email",
    },
    {
      title: "内容",
      key: "content",
      render: (_, record) => (
        <a
          onClick={() => {
            Modal.info({
              icon: null,
              width: 520,
              maskClosable: true,
              title: "评论详情",
              okText: "关闭",
              content: (
                <div
                  className="markdown"
                  dangerouslySetInnerHTML={{
                    __html: record?.content,
                  }}
                ></div>
              ),
            });
          }}
        >
          点击查看
        </a>
      ),
    },
    {
      title: "回复",
      key: "replyUserName",
      width: 120,
      dataIndex: "replyUserName",
      render: (name) => name || "无",
    },
    {
      title: "管理文章",
      key: "articleOrPage",
      width: 120,
      render: (_, record) => {
        // hostId: 文章或者页面的id， isHostInPage: 是否处于页面下的评论
        const { hostId, isHostInPage } = record;
        return hostId ? (
          <a
            href={`${setting.systemUrl}/${
              isHostInPage ? "page" : "article"
            }/${hostId}`}
            target="_blank"
          >
            前往查看
          </a>
        ) : (
          "文章可能被删除"
        );
      },
    },
    {
      title: "状态",
      key: "pass",
      render: (_, record) => (
        <Badge
          status={record.pass ? "success" : "warning"}
          text={record.pass ? "已通过" : "未通过"}
        />
      ),
    },
    {
      title: "创建时间",
      key: "createAt",
      render: (_, record) =>
        dayjs(record.createAt).format("YYYY-MM-DD hh:mm:ss"),
    },
  ];
  const getComments = useCallback((params) => {
    return CommentApi.getComments(params).then((res) => {
      setComments(res[0]);
      setParams(params);
      return res;
    });
  }, []);
  // 回复评论方法
  const reply = () => {
    if (!replyContent?.trim()) {
      return;
    }
    const userInfo = JSON.parse(sessionStorage.getItem("my_user_info_key"));
    const email = userInfo?.email || setting?.email;
    // 处理回复请求
    const handle = (email) => {
      const data = {
        name: userInfo.name,
        email,
        content: replyContent,
        parentCommentId: currentComment.parentCommentId || currentComment.id,
        hostId: currentComment.hostId,
        isHostInPage: currentComment.isHostInPage,
        replyUserName: currentComment.name,
        replyUserEamil: currentComment.email,
        // 管理员回复不发送邮件
        createByAdmin: true,
      };
      CommentApi.addComment(data).then((res) => {
        setCurrentComment(null);
        setreplyContent("");
        message.success("回复成功");
        getComments(params);
      });
    };
    if (!email) {
      SettingApi.getSettings().then((res) => {
        if (res?.smtpFromUser) {
          handle(res.smtpFromUser);
        } else {
          notification.error({
            message: "回复评论失败",
            description:
              "请前往系统设置完善 SMTP 设置，前往个人中心更新个人邮箱。",
          });
        }
      });
    } else {
      handle(email);
    }
  };

  const actionColumn = {
    title: "操作",
    key: "action",
    width: 300,
    render: (_, record) => (
      <span>
        <a
          onClick={() => {
            record.pass = true;
            CommentApi.updateComment(record.id, record).then((res) => {
              message.success("已通过");
              getComments(params);
            });
          }}
        >
          通过
        </a>
        <Divider type="vertical" />
        <a
          onClick={() => {
            record.pass = false;
            CommentApi.updateComment(record.id, record).then((res) => {
              message.success("已拒绝");
              getComments(params);
            });
          }}
        >
          拒绝
        </a>
        <Divider type="vertical" />
        <a
          onClick={() => {
            setCurrentComment(record);
          }}
        >
          回复
        </a>
        <Divider type="vertical" />
        <Popconfirm
          title="删除评论"
          okText="删除"
          cancelText="取消"
          onConfirm={() => {
            CommentApi.deleteComment(record.id).then((res) => {
              message.success("已删除");
              getComments(params);
            });
          }}
        >
          <a>删除</a>
        </Popconfirm>
      </span>
    ),
  };
  return (
    <AdminLayout>
      <SPTDataTable
        data={comments}
        defaultTotal={0}
        onSearch={getComments}
        columns={[...columns, actionColumn]}
        searchFields={[
          {
            label: "称呼",
            field: "name",
            msg: "请输入称呼",
          },
          {
            label: "Email",
            field: "email",
            msg: "请输入联系方式",
          },
          {
            label: "状态",
            field: "pass",
            msg: "请选择状态",
            children: (
              <Select style={{ width: 120 }}>
                <Select.Option key={1} value={1}>
                  已通过
                </Select.Option>
                <Select.Option key={0} value={0}>
                  未通过
                </Select.Option>
              </Select>
            ),
          },
        ]}
      />
      <Modal
        visible={!!currentComment}
        title="回复评论"
        okText="回复"
        cancelText="取消"
        onOk={reply}
        onCancel={() => {
          setreplyContent(null);
          setCurrentComment(null);
        }}
      >
        <Input.TextArea
          placeholder="支持Markdonw"
          rows={10}
          value={replyContent}
          onChange={(e) => setreplyContent(e.target.value)}
        ></Input.TextArea>
      </Modal>
    </AdminLayout>
  );
};

export default Comment;
